
package com.example.learningnote.giftbox;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.learningnote.R;

import java.util.ArrayList;
import java.util.List;

/**
 * ViewPager2 适配器，管理多页礼物
 * 适配器层 GiftPagerAdapter
 */
public class GiftPagerAdapter extends RecyclerView.Adapter<GiftPagerAdapter.PagerViewHolder> {
    private List<List<Gift>> pages; // 每页礼物列表
    private String selectedGiftId; // 选中礼物 ID
    private GiftAdapter.OnGiftClickListener onGiftClickListener; // 点击监听器

    public GiftPagerAdapter() {
        this.pages = new ArrayList<>();
    }

    /**
     * 更新礼物数据，分割为多页
     */
    public void updateGifts(List<Gift> gifts) {
        pages.clear();
        for (int i = 0; i < gifts.size(); i += 8) {
            int end = Math.min(i + 8, gifts.size());
            pages.add(new ArrayList<>(gifts.subList(i, end)));
        }
        notifyDataSetChanged();
    }

    /**
     * 更新选中状态
     */
    public void updateSelectedGiftId(String selectedGiftId) {
        this.selectedGiftId = selectedGiftId;
        notifyDataSetChanged();
    }

    /**
     * 设置点击监听器
     */
    public void setOnGiftClickListener(GiftAdapter.OnGiftClickListener listener) {
        this.onGiftClickListener = listener;
    }

    @NonNull
    @Override
    public PagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_page, parent, false);
        return new PagerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PagerViewHolder holder, int position) {
        List<Gift> pageGifts = pages.get(position);
        holder.giftAdapter.updateGifts(pageGifts);
        holder.giftAdapter.updateSelectedGiftId(selectedGiftId);
        holder.giftAdapter.setOnGiftClickListener(onGiftClickListener);
    }

    @Override
    public int getItemCount() {
        return pages.size();
    }

    static class PagerViewHolder extends RecyclerView.ViewHolder {
        RecyclerView recyclerView;
        GiftAdapter giftAdapter;

        PagerViewHolder(View itemView) {
            super(itemView);
            recyclerView = itemView.findViewById(R.id.rvGifts);
            recyclerView.setLayoutManager(new GridLayoutManager(itemView.getContext(), 4)); // 4列
            giftAdapter = new GiftAdapter(new ArrayList<>());
            recyclerView.setAdapter(giftAdapter);
        }
    }
}

